package com.cskaoyan.service.market;

import com.cskaoyan.bean.market.Issue;
import com.cskaoyan.bean.market.IssueExample;
import com.cskaoyan.bo.market.IssueCreateBo;
import com.cskaoyan.mapper.IssueMapper;
import com.cskaoyan.utils.Converter;
import com.cskaoyan.utils.PojoUtils;
import com.cskaoyan.vo.market.IssueListVo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @program: mall
 * @description:
 * @author: Mr.Mengmeng
 * @create: 2021-04-09 23:09
 **/

// 通用问题
@Service
public class IssueServiceImpl implements IssueService {
    @Autowired
    IssueMapper issueMapper;


    @Override
    public IssueListVo issueList(Integer page, Integer limit, String sort, String order, String question) {
        // 分页，排序
        PageHelper.startPage(page, limit);

        // 查询通用问题数据
        IssueExample issueExample = new IssueExample();
        issueExample.setOrderByClause(sort + " " + order);
        IssueExample.Criteria criteria = issueExample.createCriteria();
        criteria.andDeletedEqualTo(false);
        // 条件查询
        if (question != null && !"".equals(question)) {
            criteria.andQuestionLike("%" + question + "%");
        }
        List<Issue> issues = issueMapper.selectByExample(issueExample);

        // 类型转换
        ArrayList<IssueListVo.ItemsBean> itemsBeans = new ArrayList<>();
        Converter converter = PojoUtils.converter();
        converter.listConverter(issues,itemsBeans,IssueListVo.ItemsBean.class);

        PageInfo<Issue> issuePageInfo = new PageInfo<>(issues);
        long total = issuePageInfo.getTotal();

        return new IssueListVo(total,itemsBeans);
    }

    @Override
    public Issue issueUpdate(Issue issue) {
        issue.setUpdateTime(new Date());
        // 修改问题
        issueMapper.updateByPrimaryKey(issue);
        // 查询并返回
        Issue issueVo = issueMapper.selectByPrimaryKey(issue.getId());
        return issueVo;
    }

    @Override
    public void issueDelete(Issue issue) {
        // 设置为true 逻辑删除
        issue.setDeleted(true);
        issue.setUpdateTime(new Date());
        issueMapper.updateByPrimaryKey(issue);

    }

    @Override
    public Issue issueCreate(IssueCreateBo issueCreateBo) {
        Issue issue = new Issue(null,issueCreateBo.getQuestion(),issueCreateBo.getAnswer(),
                new Date(),new Date(),false);
        // 添加
        issueMapper.insert(issue);
        return issue;
    }
}
